<template>
  <div class="document-list">
    <!-- 统计卡片区域 -->
    <div class="stat-cards">
      <el-card class="stat-card">
        <template #header>
          <div class="stat-header">
            <el-icon><Document /></el-icon>
            <span>总文档数</span>
          </div>
        </template>
        <div class="stat-value">{{ documents.length }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="stat-header">
            <el-icon><Download /></el-icon>
            <span>总下载次数</span>
          </div>
        </template>
        <div class="stat-value">{{ totalDownloads }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="stat-header">
            <el-icon><Files /></el-icon>
            <span>文件总大小</span>
          </div>
        </template>
        <div class="stat-value">{{ totalSize }}</div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <el-card class="main-card">
      <template #header>
        <div class="main-header">
          <div class="left-section">
            <h2 class="title">文档管理</h2>
            <el-input
              v-model="searchQuery"
              placeholder="搜索文档..."
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="right-section">
            <el-button type="primary" @click="handleUpload">
              <el-icon><Upload /></el-icon>上传文档
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredDocuments" 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa' }"
        stripe
        border
      >
        <el-table-column width="80" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleDownload(scope.row)">
              <el-icon><Download /></el-icon>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="文档名称" min-width="300">
          <template #default="{ row }">
            <div class="document-title">
              <el-icon :size="20" class="file-icon">
                <component :is="getFileIcon(row.file_type)" />
              </el-icon>
              <el-tooltip
                :content="row.title"
                placement="top"
                :show-after="500"
                :hide-after="2000"
              >
                <span class="title-text">{{ row.title }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="file_type" label="类型" width="100" align="center" />
        <el-table-column prop="file_size_formatted" label="大小" width="100" align="center" />
        <el-table-column prop="upload_time" label="上传时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.upload_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="download_count" label="下载次数" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getDownloadTagType(row.download_count)">
              {{ row.download_count }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文档" width="30%" center destroy-on-close>
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :data="uploadData"
        :headers="{
          'X-Requested-With': 'XMLHttpRequest',
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        }"
        name="file"
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传 DOC, DOCX, PDF, XLS, XLSX, PPT, PPTX 等格式文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {
  Document,
  Files,
  Download,
  Upload,
  Search,
  Delete,
  Document as DocIcon,
  Grid as ExcelIcon,
  Picture as PptIcon,
  DocumentCopy as PdfIcon,
  More as OtherIcon,
} from '@element-plus/icons-vue'

const API_BASE_URL = 'http://localhost:8000/api'
const uploadUrl = `${API_BASE_URL}/documents/`

// 创建axios实例并添加认证token
const api = axios.create({
  baseURL: API_BASE_URL
})

// 添加请求拦截器
api.interceptors.request.use(config => {
  const token = localStorage.getItem('access_token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

const documents = ref([])
const loading = ref(false)
const uploadDialogVisible = ref(false)
const uploadData = ref({})
const searchQuery = ref('')

// 计算属性
const filteredDocuments = computed(() => {
  if (!searchQuery.value) return documents.value
  const query = searchQuery.value.toLowerCase()
  return documents.value.filter(doc => 
    doc.title.toLowerCase().includes(query) ||
    doc.file_type.toLowerCase().includes(query)
  )
})

const totalDownloads = computed(() => {
  return documents.value.reduce((sum, doc) => sum + doc.download_count, 0)
})

const totalSize = computed(() => {
  const totalBytes = documents.value.reduce((sum, doc) => sum + doc.file_size, 0)
  return formatFileSize(totalBytes)
})

// 方法
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getFileIcon = (fileType) => {
  const type = fileType.toLowerCase()
  if (type === 'doc' || type === 'docx') return DocIcon
  if (type === 'xls' || type === 'xlsx') return ExcelIcon
  if (type === 'ppt' || type === 'pptx') return PptIcon
  if (type === 'pdf') return PdfIcon
  return OtherIcon
}

const getDownloadTagType = (count) => {
  if (count === 0) return 'info'
  if (count < 5) return ''
  if (count < 10) return 'success'
  return 'warning'
}

const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

// 获取文档列表
const fetchDocuments = async () => {
  loading.value = true
  try {
    const response = await api.get('/documents/')
    documents.value = response.data
  } catch (error) {
    ElMessage.error('获取文档列表失败')
    console.error('Error fetching documents:', error)
  } finally {
    loading.value = false
  }
}

// 处理上传按钮点击
const handleUpload = () => {
  uploadDialogVisible.value = true
}

// 上传前验证
const beforeUpload = (file) => {
  // 检查文件大小（2GB限制）
  const maxSize = 2 * 1024 * 1024 * 1024 // 2GB
  if (file.size > maxSize) {
    ElMessage.error(`文件大小不能超过2GB，当前文件大小为 ${(file.size / (1024*1024*1024)).toFixed(2)}GB`)
    return false
  }
  return true
}

// 上传成功处理
const handleUploadSuccess = (response, uploadFile) => {
  ElMessage.success('上传成功')
  getDocuments() // 刷新文档列表
}

// 上传失败处理
const handleUploadError = (error, uploadFile) => {
  let errorMessage = '上传失败'
  if (error.response && error.response.data && error.response.data.error) {
    errorMessage = error.response.data.error
  }
  ElMessage.error(errorMessage)
}

// 处理下载
const handleDownload = async (doc) => {
  try {
    const response = await api.get(`/documents/${doc.id}/download/`, {
      responseType: 'blob'
    })
    
    // 从响应头中获取文件名
    const contentDisposition = response.headers['content-disposition']
    let filename = doc.title
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename="(.+)"/)
      if (filenameMatch) {
        filename = decodeURIComponent(filenameMatch[1])
      }
    }
    
    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = window.document.createElement('a')
    link.href = url
    link.setAttribute('download', filename)
    window.document.body.appendChild(link)
    link.click()
    window.document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    // 刷新文档列表以更新下载计数
    fetchDocuments()
    
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('Download error:', error)
    ElMessage.error(error.response?.data?.error || '下载失败')
  }
}

// 处理删除
const handleDelete = (document) => {
  ElMessageBox.confirm(
    '确定要删除这个文档吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await api.delete(`/documents/${document.id}/`)
      ElMessage.success('删除成功')
      fetchDocuments()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('Error deleting document:', error)
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchDocuments()
})
</script>

<style scoped>
.document-list {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
  margin-top: 10px;
}

.main-card {
  margin-bottom: 20px;
}

.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.title {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.search-input {
  width: 300px;
}

.document-title {
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: 100%;
  
  .file-icon {
    flex-shrink: 0;
    color: #909399;
  }

  .title-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #303133;
    font-size: 14px;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
}

/* 上传对话框样式 */
.upload-demo {
  display: flex;
  justify-content: center;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 200px;
}

.el-upload__tip {
  text-align: center;
  margin-top: 10px;
  color: #909399;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .main-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .left-section {
    flex-direction: column;
    width: 100%;
  }
  
  .search-input {
    width: 100%;
  }
}
</style> 